package org.meetunexpectedly.config;

import org.springframework.beans.factory.InitializingBean;

import javax.annotation.PreDestroy;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Description: DB任务定时执行器(用于)
 * @Author: pupil
 * @Date: 2024/08/23 下午 8:59
 */
@Deprecated
public class TimedActuator implements InitializingBean {

    // 任务队列
    private static ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>();

    // 定时任务线程池
    private static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);

    // 定时时间(1s)
    private static final long TIMED_TIME = 1000;

    // 时间单位(毫秒)
    private static final TimeUnit TIME_UNIT = TimeUnit.MILLISECONDS;

    // 提交任务
    public static void putTask(Runnable runnable) {
        queue.add(runnable);
    }

    // 执行任务
    private void runTask() {
        Runnable runnable = queue.poll();
        if (runnable != null) {
            runnable.run();
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        scheduler.scheduleAtFixedRate(this::runTask, 0, TIMED_TIME, TIME_UNIT);
    }

    // 确保在Spring容器关闭时关闭线程池
    @PreDestroy
    public void destroy() {
        scheduler.shutdown();
    }
}
